package com.googlecode.gwtbb.client.only.widget.form.entry;

import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.googlecode.gwtbb.client.only.widget.basic.NiceCheckBox;
import com.googlecode.gwtbb.client.shared.validation.FieldId;
import com.googlecode.gwtbb.client.shared.util.StringUtils;

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Feb 5, 2009
 */
public class LabeledNiceCheckGroupFormEntry extends LabeledFormEntry {
private List<NiceCheckBox> entryNiceCheckGroup;
	private Panel checkBoxesPanel;

	public List<NiceCheckBox> getEntryNiceCheckGroup() {
		return entryNiceCheckGroup;
	}

	public void setEntryNiceCheckGroup(List<NiceCheckBox> entryNiceCheckGroup) {
		this.entryNiceCheckGroup = entryNiceCheckGroup;
		checkBoxesPanel.clear();
		for (NiceCheckBox ncb : entryNiceCheckGroup)
			checkBoxesPanel.add(ncb);
	}

	public LabeledNiceCheckGroupFormEntry(FieldId fieldId, String defaultValue, int labelRow, int labelCol, String labelText, List<NiceCheckBox> entryNiceCheckGroup) {
		super(fieldId, defaultValue, labelRow, labelCol, labelText);
		checkBoxesPanel = new VerticalPanel();
		setEntryNiceCheckGroup(entryNiceCheckGroup);
		clearValue();
	}

	public Widget getEntryWidget() {
		return checkBoxesPanel;
	}

	public String getValue() {
		return StringUtils.join(getValues(), ",");
	}

	public List<String> getValues() {
		List<String> retVal = new ArrayList<String>(entryNiceCheckGroup.size());
		for (NiceCheckBox ncb : entryNiceCheckGroup)
			if (ncb.isChecked())
				retVal.add(ncb.getName());
		return retVal;
	}

	public void setValue(String value) {
		if (value == null) {
			for (NiceCheckBox ncb : entryNiceCheckGroup)
				ncb.setChecked(false);
		} else {
			List<String> values = Arrays.asList(value.split(","));
			for (NiceCheckBox ncb : entryNiceCheckGroup)
				ncb.setChecked(values.contains(ncb.getName()));
		}
	}
}
